<template>
  <div class="scrollable-content">
    <div class="stat-cards">
      <div class="stat-card" v-for="stat in stats" :key="stat.title">
        <div class="title">{{ stat.title }}</div>
        <div class="value">￥{{ stat.value }}</div>
      </div>
    </div>

    <!-- 折线图区域 -->
    <el-card class="chart-container">
      <div class="chart-header">
        <h2>近七日成交额趋势</h2>
      </div>
      <div class="chart-wrapper">
        <div ref="lineChart" style="width: 100%; height: 300px;"></div>
      </div>
    </el-card>

    <!-- 用户信息列表 -->
    <el-card class="user-list">
      <div class="list-header">
        <h2>付款用户信息</h2>
        <div class="list-actions">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索用户..."
            prefix-icon="el-icon-search"
            style="width: 200px; margin-right: 15px;"
            @keyup.enter="handleSearch"
          ></el-input>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>
      
      <el-table :data="pagedUserData" style="width: 100%" v-loading="loading">
        <el-table-column prop="userName" label="用户名" width="180">
          <template #default="scope">
            <div class="user-cell">
              <el-avatar :src="scope.row.userAvatar" size="small"></el-avatar>
              <span style="margin-left: 10px">{{ scope.row.userName }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="userPhone" label="手机号" width="150"></el-table-column>
        
        <el-table-column prop="transactionAmount" label="付款金额" width="120">
          <template #default="scope">
            <span class="amount-value">¥ {{ scope.row.transactionAmount }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="groupTourName" label="报名跟团游"></el-table-column>
        
        <el-table-column prop="registrationTime" label="付款时间" width="180">
          <template #default="{row}">
            {{ formatDate(row.registrationTime) }}
          </template>
        </el-table-column>
      </el-table>
      
      <div class="demo-pagination-block" style="display: flex; justify-content: center; margin-top: 18px;">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  name: 'Money',
  data() {
    return {
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      stats: [
        { title: '今日成交额', value: 0 },
        { title: '本月成交额', value: 0 },
        { title: '总成交额', value: 0 }
      ],
      userData: [],
      searchParams: {
        keyword: '',
        startDate: '',
        endDate: ''
      },
      lineChartData: {
        dates: [],
        amounts: []
      }
    };
  },
  computed: {
    pagedUserData() {
      return this.userData;
    }
  },
  mounted() {
    this.fetchStatsData();
    this.initLineChart();
    this.fetchUserData();
  },
  methods: {
    formatDate(date) {
      if (!date) return '';
      try {
        return new Date(date).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-');
      } catch (e) {
        return date;
      }
    },
      formatSimpleDate(dateStr) {
        // 确保传入的是Date对象
        const date = new Date(dateStr);
        // 使用UTC方法避免时区影响
        return `${date.getUTCMonth() + 1}/${date.getUTCDate()}`;
      },
        async fetchStatsData() {
      try {
        // 获取统计卡片数据
        const statsRes = await this.$http.get('http://localhost:8080/gtr/stats');
        if (statsRes.data) {
          const statsData = statsRes.data;
          this.stats = [
            { title: '今日成交额', value: statsData.todayAmount || 0 },
            { title: '本月成交额', value: statsData.monthAmount || 0 },
            { title: '总成交额', value: statsData.totalAmount || 0 }
          ];
        }
        
        // 在fetchStatsData方法中修改：
        const trendRes = await this.$http.get('http://localhost:8080/gtr/trend');
        if (trendRes.data) {
          const trendData = trendRes.data;
          
          // 确保数据按日期升序排列
          trendData.sort((a, b) => new Date(a.date) - new Date(b.date));
          
          this.lineChartData = {
            dates: trendData.map(item => this.formatSimpleDate(item.date)),
            amounts: trendData.map(item => parseFloat(item.amount) || 0)
          };
          
          // 动态生成x轴标签
          this.generateChartLabels(trendData);
          this.initLineChart();
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
        this.$message.error('获取统计数据失败');
      }
    },
    async fetchUserData() {
      this.loading = true;
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchParams.keyword
        };
        
        // 添加调试日志
        console.log('请求参数:', params);
        
        const res = await this.$http.get('http://localhost:8080/gtr/page/search', { params });
        
        // 打印完整响应
        console.log('完整响应:', res);
        
        // 处理不同响应结构
        let data = res.data;
        if (data && data.data) {
          data = data.data; // 处理嵌套的data结构
        }
        
        if (data && Array.isArray(data.list)) {
          this.userData = data.list;
          this.totalCount = data.total || data.list.length;
        } else if (Array.isArray(data)) {
          this.userData = data;
          this.totalCount = data.length;
        } else {
          console.warn('未识别的响应结构:', data);
          this.userData = [];
          this.totalCount = 0;
        }
                  // 转换金额为数字类型
          this.userData.forEach(item => {
            if (typeof item.transactionAmount === 'string') {
              item.transactionAmount = parseFloat(item.transactionAmount) || 0;
            }
          });
        // 打印最终使用的数据
        console.log('最终用户数据:', this.userData);
        
      } catch (error) {
        console.error('获取用户数据失败:', error);
        this.userData = [];
        this.totalCount = 0; 
      } finally {
        this.loading = false;
      }
    },
    generateChartLabels(trendData) {
      const now = new Date();
      this.chartLabels = trendData.map(item => {
        const date = new Date(item.date);
        const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24));
        return diffDays === 0 ? '今天' : 
              diffDays === 1 ? '昨天' : 
              diffDays === 2 ? '前天' : 
              `${diffDays}天前`;
      }).reverse(); // 确保顺序正确
    },

    handlePageChange(val) {
      this.currentPage = val;
      this.fetchUserData();
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchUserData();
    },
    
    handleSearch() {
      this.currentPage = 1;
      this.fetchUserData();
    },
        resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    initLineChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
      
      this.chartInstance = echarts.init(this.$refs.lineChart);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            return `${params[0].axisValue}: ¥${params[0].data.toLocaleString()}`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chartLabels || ['7天前', '6天前', '5天前', '4天前', '3天前', '前天', '昨天'],
          axisLine: {
            lineStyle: {
              color: '#409EFF'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '金额（元）',
          nameTextStyle: {
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#409EFF'
            }
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '成交额',
            type: 'line',
            data: this.lineChartData.amounts,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#409EFF'
            },
            lineStyle: {
              width: 3,
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#66b1ff' },
                { offset: 1, color: '#409EFF' }
              ])
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ])
            }
          }
        ]
      };
      
      this.chartInstance.setOption(option);
      
      // 修正这里：使用 this.chartInstance 而不是 chart
      window.addEventListener('resize', () => {
        this.chartInstance.resize();
      });
    }
  }
};
</script>

<style scoped src="/public/css/MainLayout.css">

</style>